package com.ncmem.up6.store;

import com.ncmem.up6.utils.PathTool;
import com.ncmem.up6.model.FileInf;

import java.io.*;

/**
 *文件续传类，负责将文件块写入硬盘中
 */
public class FileBlockWriter {
	public StorageType storage;//写入器类型
	
	public FileBlockWriter()
	{
		this.storage = StorageType.IO;
	}
	
	public String make(FileInf file) throws IOException {
		File ps = new File(file.pathSvr);
		PathTool.createDirectory(ps.getParent());

		RandomAccessFile raf = new RandomAccessFile(file.pathSvr, "rw");
		raf.setLength(file.lenLoc);//fix:以原始大小创建文件
		raf.close();
		return "";
	}
	
	public String write(FileInf file, ByteArrayOutputStream ostm) throws IOException {
		if (!PathTool.exist(file.pathSvr))
			throw new IOException("文件不存在:"+file.pathSvr);

		byte[] data = ostm.toByteArray();

		//bug:在部分服务器中会出现错误：(另一个程序正在使用此文件，进程无法访问。)
		RandomAccessFile raf = new RandomAccessFile(file.pathSvr,"rw");
		//定位文件位置
		raf.seek(file.blockOffset);
		raf.write(data);
		raf.close();
		return "ok";
	}

	/**
	 * 写入最后一块数据=>所有文件块上传完毕
	 * @param file
	 * @return
	 */
	public boolean writeLastPart(FileInf file) throws IOException {
		return  true;
	}
}